package cn.edu.cqu.android.phone.loaddata;
import java.io.File;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;

import cn.edu.cqu.android.phone.domain.Contacttel;
import cn.edu.cqu.android.phone.domain.Sms;
import cn.edu.cqu.android.phone.domain.Users;


public class OldDataSource {
    private static java.sql.Connection con = null;
    String url;
    ResultSet rs=null;
    static{
    	try {
			Class.forName(Schema.SQLITEDRIVER);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	public OldDataSource(String database) throws SQLException, ClassNotFoundException{
		url=database;
	}
	public void connect() throws SQLException{
		con = DriverManager.getConnection(url);						
		
	}
	
	public void close() throws SQLException{
		con.close();
	}
	
	public static void main(String[] args) throws Exception{
		OldDataSource oldDataSource=new OldDataSource(Schema.OLDURL4SMS);
		oldDataSource.connect();
		
		oldDataSource.close();
	}
	/**
	 * just a temp var.
	 */
	String  temp;
	public void addSms(Users user,Session session,Date date) throws SQLException{
		rs=con.createStatement().executeQuery("select address,date,read,status,type,body  from sms where date >"+date.getTime()+" order by date");
		String address=null;
		String substring=null;
		int type;
		int i=0;
		while(rs.next()){
			Sms sms=new Sms();
			address=rs.getString("address");
			if(address==null){
				System.out.println("\naddress is null:( body:"+(((temp=rs.getString("body"))==null)?"null":temp));
				continue;
			}
			if(address.startsWith("+")){
				if(address.startsWith("+86"))
					substring=address.substring(3);
			}else if(address.startsWith("12520")){
					substring=address.substring(5);
			}else{
				substring=address;
			}
			List<Contacttel>cts= session.createQuery("from Contacttel ct where ct.tel='"+substring+"'").list();
			if(cts.size()>0){
				sms.setContacts(cts.get(0).getContacts());
				sms.setTel(substring);
			}else{
				sms.setTel(address);
			}
			//sms.setTel(substring);
			
			sms.setUsers(user);
			sms.setBody(rs.getString("body"));
			type=rs.getInt("type");
			sms.setDirection(type==1?"1":"2");
			sms.setIsOk((rs.getInt("status")==-1||rs.getInt("status")==0)?"y":"n");
			sms.setDate(new Time(rs.getLong("date")));
			session.save(sms);
			System.out.print(".");
			if(++i%100==0){
				System.out.println("\n"+i);
			}
		}
		rs.close();
	}

}
